package com.weir.resilience4j.consumer;

import java.time.Duration;
import java.util.function.Supplier;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import io.github.resilience4j.circuitbreaker.CircuitBreakerRegistry;
import io.github.resilience4j.ratelimiter.RateLimiter;
import io.github.resilience4j.ratelimiter.RateLimiterConfig;
import io.github.resilience4j.ratelimiter.RateLimiterRegistry;
import io.github.resilience4j.retry.annotation.Retry;
import io.vavr.control.Try;

@Service
public class HelloService3 {

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    CircuitBreakerRegistry circuitBreakerRegistry;
//限流
    public void hello2(String name) {
        RateLimiterConfig config = RateLimiterConfig.custom()
                .limitRefreshPeriod(Duration.ofMillis(5000))
                .limitForPeriod(1)
                .timeoutDuration(Duration.ofMillis(6000))
                .build();
        RateLimiterRegistry rateLimiterRegistry = RateLimiterRegistry.of(config);
        RateLimiter rateLimiter = RateLimiter.of("backendC", config);
        Supplier<String> supplier = RateLimiter.decorateSupplier(rateLimiter, () ->
                restTemplate.getForObject("http://localhost:9999/hell?name={1}", String.class, name)
        );
        for (int i = 0; i < 5; i++) {
            Try<String> aTry = Try.ofSupplier(supplier);
            System.out.println(aTry.get());
        }
    }


}
